<!--
 * @Author: Allen
 * @Date: 2021-03-04 14:26:13
 * @Description: 抱怨身处黑暗，不如提灯前行。愿你在自己存在的地方，成为一束光，照亮世界的一角
 * @LastEditTime: 2021-03-18 11:33:15
 * @LastEditors: Allen
 * @FilePath: \dmocdms_webend\src\views\se\basicData\warrantyPeriodSetting\index.vue
 * @Additional: 保修单设置
-->

<template>
  <div class="app-container app-container-table">
    <div class="eltabs">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="备件分类" name="first">
          <one-table-template
            ref="multipleTable1"
            :key="oneTableKey"
            :dynamic-buttons="tableButtons"
            :dynamic-components="tableComponents"
            :dynamic-api-config="apiConfig"
            :dynamic-table-cols="tableCols"
            :dynamic-form-fields="formField"
            :dynamic-is-show-select="false"
            :dynamic-is-init-table="true"
            :dynamic-api-style="'restful'"
          />
          <edit
            :key="editPopupsKey"
            :dynamic-edit-row-data="editRowData"
            :popups-visible="editPopupsVisible"
            :popups-state="editPopupsState"
            :is-show-chooes="isShowChooes"
            :prop-data="propData"
            @close="close"
          />
        </el-tab-pane>
        <el-tab-pane label="保修期限" name="second">
          <one-table-template
            ref="multipleTable"
            :key="oneTableKey"
            :dynamic-buttons="tableButtons1"
            :dynamic-components="tableComponents1"
            :dynamic-api-config="apiConfig1"
            :dynamic-table-cols="tableCols1"
            :dynamic-form-fields="formField1"
            :dynamic-is-show-select="false"
            :dynamic-is-init-table="true"
            :dynamic-api-style="'restful'"
          />
          <edits
            :key="editPopupsKey1"
            :dynamic-edit-row-data="editRowData"
            :popups-visible="editPopupsVisible1"
            :popups-state="editPopupsState1"
            :prop-data="propData"
            @close="close"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import OneTableTemplate from '@/components/templates/oneTable'
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import { formMixins } from '@/components/mixins/formMixins'
import request from '../../../../utils/request.js'

export default {
  components: {
    OneTableTemplate,
    Edit: () => import('./edit'),
    Edits: () => import('./edit2')
  },
  mixins: [oneTableWithViewTemplateMixins, formMixins],
  // 组件混入对象
  data() {
    return {
      activeName: 'first',
      apiConfig: {
        ServiceCode: 'findWarrantySettings',
        APIUrl:
          '/mp/e3sh/aftersale/WarrantySettingsService/findWarrantySettings.do'
      },
      apiConfig1: {
        ServiceCode: 'findGuaranteeTime',
        APIUrl:
          '/mp/e3sh/aftersale/WarrantySettingsService/findGuaranteeTime.do'
      },
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTables(),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        },
        {
          compKey: 'btnKey3',
          size: 'small',
          name: 'add',
          clickEvent: this.add,
          text: this.$t('sys.button.add'), // 新增
          position: 'right'
        },
        {
          compKey: 'btnKey6',
          text: '导入',
          category: 've',
          codeField: 'fileChannel',
          position: 'upload',
          isMust: true
        }, // 导入
        {
          compKey: 'btnKey5',
          size: 'small',
          name: 'importTemplateDownload',
          position: 'left',
          clickEvent: () => this.downloadTemplate(),
          text: '模板下载' // "模板下载"
        }
      ],
      tableButtons1: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        },
        {
          compKey: 'btnKey3',
          size: 'small',
          name: 'add',
          clickEvent: this.addTwo,
          text: this.$t('sys.button.add'), // 新增
          position: 'right'
        }
      ],
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '保修分类：',
              codeField: 'parTimeClass',
              component: () =>
                import('@/components/org/dropdownList/dropdownList'),
              options: [],
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '备件分类：',
              codeField: 'partClass',
              component: () =>
                import('@/components/org/dropdownList/dropdownList'),
              options: [],
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '备件编码：',
              codeField: 'partNO',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: '备件名称：',
              codeField: 'partName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            }
          ],
      tableComponents1:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '保修分类：',
              codeField: 'parTimeClass',
              component: () =>
                import('@/components/org/dropdownList/dropdownList'),
              options: [],
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '备件分类：',
              codeField: 'partClass',
              component: () =>
                import('@/components/org/dropdownList/dropdownList'),
              options: [],
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '保修期里程：',
              codeField: 'partMile',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: '保修期时间：',
              codeField: 'partTimeLimit',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            }
          ],
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'releaseId',
              label: '主键ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'controlBtn1',
              label: '操作',
              minWidth: 180,
              isComponent: true,
              comps: [
                {
                  compKey: 'propKey1',
                  labelName: '编辑',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => this.edit(index)
                },
                {
                  compKey: 'propKey2',
                  labelName: '删除',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => this.delete(index)
                }
              ]
            },
            {
              prop: 'parTimeClass',
              label: '保修分类'
            },
            {
              prop: 'partClass',
              label: '备件分类'
            },
            {
              prop: 'partNO',
              label: '备件编码'
            },
            {
              prop: 'partName',
              label: '备件名称'
            }
          ],
      tableCols1:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'releaseId',
              label: '主键ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'parTimeClass',
              label: '保修分类'
            },
            {
              prop: 'partClass',
              label: '备件分类'
            },
            {
              prop: 'partMile',
              label: '保修期里程（KM）'
            },
            {
              prop: 'partTimeLimit',
              label: '保修期时间（月）'
            }
          ],
      formField: {
        parTimeClass: '',
        partClass: '',
        partNO: '',
        partName: ''
      },
      formField1: {
        parTimeClass: '',
        partClass: '',
        partMile: '',
        partTimeLimit: ''
      },
      isShowChooes: false,
      changeTabState: 'frist',
      // 新增、编辑弹窗状态
      editPopupsVisible1: false,
      // 新增、编辑弹窗Key
      editPopupsKey1: '',
      // 新增、编辑弹窗状态（add/edit/view）
      editPopupsState1: '',
      propData: {}
    }
  },
  mounted() {
    this.dropdownList()
  },
  methods: {
    queryTables() {
      this.$utils.validataMoth(this, 'validpage')
      this.$refs['multipleTable1'].queryTable()
    },

    handleClick(e) {
      this.changeTabState = e.name
    },
    dropdownList() {
      const dropdownList = {
        partimeClassData: {},
        partClassData: {},
        tables: this.$refs['multipleTable1'],
        table: this.$refs['multipleTable']
      }
      new Promise((resolve, reject) => {
        var partimeClassApi = {
          apiUrl:
            '/mp/e3sh/aftersale/WarrantySettingsService/partimeClassFind.do',
          variables: {}
        }
        this.$requestAPI(partimeClassApi, '').then((response) => {
          var res = response.rows
          res.map((item) => {
            this.tableComponents[0].options.push({
              label: item.partimeClassName,
              value: item.parTimeClass
            })
            this.tableComponents1[0].options.push({
              label: item.partimeClassName,
              value: item.parTimeClass
            })
          })
          dropdownList.partimeClassData = this.tableComponents[0].options
        })
        var partClassApi = {
          apiUrl: '/mp/e3sh/aftersale/WarrantySettingsService/partClassFind.do',
          variables: {}
        }
        this.$requestAPI(partClassApi, '').then((response) => {
          var res = response.rows
          res.map((item) => {
            this.tableComponents[1].options.push({
              label: item.partClassName,
              value: item.partClass
            })
            this.tableComponents1[1].options.push({
              label: item.partClassName,
              value: item.partClass
            })
          })
          dropdownList.partClassData = this.tableComponents[1].options
        })
        resolve('成功')
      }).then((res) => {
        console.log(res)
        this.propData = dropdownList
      })
    },
    addTwo() {
      this.editPopupsState1 = 'add'
      this.editPopupsVisible1 = true
      this.editPopupsKey1 = this.$utils.generateId()
    },
    edit(index) {
      var curIndex = index
      const that = this.$refs['multipleTable1']
      if (curIndex === undefined || curIndex === null) {
        var currentRow
        if (that.isMul === true) {
          // 多选
          var selectData = that.selection
          if (selectData.length > 0) {
            currentRow = selectData[0]
          }
        } else {
          // 单选
          currentRow = that.currentRow
        }
        if (currentRow) {
          curIndex = currentRow.index
        }
      }

      if (curIndex === undefined || curIndex === null) {
        this.$alert('请选择需要修改的数据', '提示')
        return
      }
      this.editRowData = that.list[curIndex]
      this.showEdit('edit')
    },
    delete(index) {
      this.$confirm('确定要删除吗?', '提示', {
        type: 'warning'
      }).then(() => {
        const parTimeClassID = this.$refs['multipleTable1'].list[index]
          .parTimeClassID
        const deleteApi = {
          apiUrl:
          '/mp/e3sh/aftersale/WarrantySettingsService/deleteWarrantySettings.do',
          variables: { parTimeClassID: parTimeClassID }
        }
        this.$requestAPI(deleteApi, '').then((response) => {
          console.log(response)
          if (response.result == 1) {
            this.$message({
              message: response.msg,
              type: 'warn',
              duration: 1000
            })
            this.$refs['multipleTable1'].queryTable()
          }
        })
      })
    },
    // downloadTemplate() {
    //   request({
    //     url: '/mp/e3sh/aftersale/WarrantySettingsService/downloadTemplate.do',
    //     method: 'POST',
    //     headers: {
    //       'Content-Type': 'application/json;charset=UTF-8'
    //     },
    //     responseType: 'blob'
    //   }).then((res) => {
    //     console.log(res,'res')
    //     const blob = new Blob([res], { type: 'application/vnd.ms-excel' }) // res就是接口返回的文件流了
    //     console.log(blob,'blob')
    //     const objectUrl = URL.createObjectURL(blob)
    //     window.location.href = objectUrl
    //   })
    // },
    downloadTemplate() {
      const fileName = this.$utils.fileNameWithTime('保修期设置模板.xlsx')
      this.$requestAPI({
        apiUrl: '/mp/e3sh/aftersale/WarrantySettingsService/downloadTemplate.do',
        variables: { dataType: 'excel' }
      }).then(res => {
        this.$utils.downloadFile(res, fileName)
      }).catch(err => {
        console.log(err)
      })
    },
    handFileListChange(file, fileList) {},
    // 上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传。
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: '文件大小不能超过50M',
          type: 'warning'
        })
        return false
      }
      const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (fileType != 'xls' && fileType != 'xlsx') {
        this.$message({
          message: '只能导入后缀为xls,xlsx的文件！',
          type: 'warning'
        })
        return false
      }
      return true
    },
    handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: '导入中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const that = this
      const url =
        '/mp/e3sh/aftersale/WarrantySettingsService/improtTemplate.do'
      that
        .$requestUpload(url, param)
        .then((response) => {
          loading.close()
          if (response.result === '1') {
            this.$message({
              message: '导入成功',
              type: 'success'
            })
            that.queryTables()
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            })
          }
        })
    }
  }
}
</script>

<style>
.app-container {
  background: #fff;
}
</style>
